import http.client
import json
import os
import datetime
from urllib.parse import urlparse

try:
    import toml
except ImportError:
    print("错误: 需要安装 toml 库，请运行: pip install toml")
    exit(1)

class FlowUsToSiliconFlow:
    def __init__(self, config_file="config.toml"):
        # 加载配置文件
        self.config = self.load_config(config_file)
        
        # API配置
        self.flowus_token = self.config['flowus']['token']
        self.siliconflow_token = self.config['siliconflow']['token']
        
        # 从URL中提取页面ID
        self.flowus_url = self.config['flowus']['url']
        self.page_id = self.extract_page_id(self.flowus_url)
        self.parent_page_id = self.config['flowus']['parent_page_id']
        
        # 输出配置
        self.output_filename = self.config['output']['filename']
        self.log_filename = self.config['output'].get('log_file', 'data.log')
        
        # 新页面配置
        self.new_page_config = self.config['new_page']
        self.block_settings = self.config['block_settings']
        self.database_config = self.config['database']
        
        # 缓存已处理的页面，避免重复获取
        self.processed_pages = set()
        
    def load_config(self, config_file):
        """加载TOML配置文件"""
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                return toml.load(f)
        except FileNotFoundError:
            raise FileNotFoundError(f"配置文件 {config_file} 未找到")
        except toml.TomlDecodeError:
            raise ValueError(f"配置文件 {config_file} 格式错误")
        except Exception as e:
            raise Exception(f"加载配置文件时出错: {e}")
    
    def extract_page_id(self, url):
        """从FlowUs URL中提取页面ID"""
        parsed_url = urlparse(url)
        path_parts = parsed_url.path.split('/')
        if len(path_parts) >= 2:
            return path_parts[-1]
        else:
            raise ValueError("无法从URL中提取页面ID")
    
    def get_flowus_page_content(self):
        """获取FlowUs页面内容"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            # 构建请求URL
            request_url = f"/v1/blocks/{self.page_id}/children?recursive=true"
            
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                return json.loads(data.decode("utf-8"))
            else:
                print(f"获取FlowUs页面失败，状态码: {res.status}")
                return None
                
        except Exception as e:
            print(f"获取FlowUs页面时出错: {e}")
            return None
    
    def get_page_content_by_id(self, page_id):
        """根据页面ID获取页面内容"""
        if page_id in self.processed_pages:
            return None
            
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            # 获取页面块内容
            request_url = f"/v1/blocks/{page_id}/children?recursive=true"
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                self.processed_pages.add(page_id)
                return json.loads(data.decode("utf-8"))
            else:
                print(f"获取关联页面内容失败，状态码: {res.status}")
                return None
                
        except Exception as e:
            print(f"获取关联页面内容时出错: {e}")
            return None
    
    def get_page_details(self, page_id):
        """获取页面的详细信息，包括所有属性"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            # 获取页面信息
            request_url = f"/v1/pages/{page_id}"
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                page_data = json.loads(data.decode("utf-8"))
                return page_data
            else:
                print(f"获取页面详细信息失败，状态码: {res.status}")
                return None
                
        except Exception as e:
            print(f"获取页面详细信息时出错: {e}")
            return None
    
    def get_page_title_by_id(self, page_id):
        """根据页面ID获取页面标题"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            # 获取页面信息
            request_url = f"/v1/pages/{page_id}"
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                page_data = json.loads(data.decode("utf-8"))
                # 提取页面标题
                if 'properties' in page_data and 'title' in page_data['properties']:
                    title_prop = page_data['properties']['title']
                    if 'title' in title_prop:
                        titles = title_prop['title']
                        if titles and len(titles) > 0:
                            return titles[0].get('plain_text', '无标题')
                return "无标题"
            else:
                return "未知页面"
                
        except Exception as e:
            print(f"获取页面标题时出错: {e}")
            return "未知页面"
    
    def extract_text_from_page_blocks(self, blocks_data):
        """从页面块数据中提取文本内容"""
        text_content = []
        
        if blocks_data and 'results' in blocks_data:
            for block in blocks_data['results']:
                if block['type'] == 'paragraph' and 'data' in block:
                    rich_text = block['data'].get('rich_text', [])
                    for text_item in rich_text:
                        if text_item['type'] == 'text' and 'plain_text' in text_item and text_item['plain_text']:
                            text_content.append(text_item['plain_text'])
        
        return '\n'.join(text_content)
    
    def extract_database_info_from_blocks(self, blocks_data):
        """从块数据中提取数据库信息"""
        database_blocks = []
        mentioned_databases = []
        
        if blocks_data and 'results' in blocks_data:
            for block in blocks_data['results']:
                # 检查是否是直接嵌入的数据库块
                if block['type'] in ['child_database', 'database']:
                    database_info = {
                        'id': block['id'],
                        'type': block['type'],
                        'title': self.extract_database_title(block),
                        'created_time': block.get('created_time'),
                        'last_edited_time': block.get('last_edited_time'),
                        'source': 'embedded'
                    }
                    database_blocks.append(database_info)
                
                # 检查是否是提及的数据库（页面引用）
                elif (block['type'] == 'paragraph' and 
                      'data' in block and 
                      'rich_text' in block['data']):
                    for text_item in block['data']['rich_text']:
                        if (text_item['type'] == 'mention' and 
                            'mention' in text_item and 
                            text_item['mention']['type'] == 'page'):
                            mentioned_page_id = text_item['mention']['page']['id']
                            # 检查提及的页面是否是数据库
                            if self.is_database(mentioned_page_id):
                                db_info = self.get_database_info(mentioned_page_id)
                                if db_info:
                                    db_info['source'] = 'mentioned'
                                    mentioned_databases.append(db_info)
        
        # 合并两种类型的数据库，去重
        all_databases = database_blocks
        seen_ids = {db['id'] for db in database_blocks}
        
        for db in mentioned_databases:
            if db['id'] not in seen_ids:
                all_databases.append(db)
                seen_ids.add(db['id'])
        
        return all_databases
    
    def is_database(self, page_id):
        """检查页面是否是数据库"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            request_url = f"/v1/databases/{page_id}"
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            return res.status == 200
        except:
            return False
    
    def get_database_info(self, database_id):
        """获取数据库信息"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            request_url = f"/v1/databases/{database_id}"
            conn.request("GET", request_url, '', headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                db_data = json.loads(data.decode("utf-8"))
                return {
                    'id': database_id,
                    'type': 'database',
                    'title': self.extract_database_title_from_db_object(db_data),
                    'created_time': db_data.get('created_time'),
                    'last_edited_time': db_data.get('last_edited_time'),
                    'source': 'mentioned'
                }
            else:
                return None
        except Exception as e:
            print(f"获取数据库信息时出错: {e}")
            return None
    
    def extract_database_title_from_db_object(self, db_object):
        """从数据库对象中提取标题"""
        if 'title' in db_object:
            title_data = db_object['title']
            if isinstance(title_data, list):
                title_parts = []
                for item in title_data:
                    if isinstance(item, dict):
                        if 'text' in item and 'content' in item['text']:
                            title_parts.append(item['text']['content'])
                        elif 'plain_text' in item:
                            title_parts.append(item['plain_text'])
                return ''.join(title_parts) if title_parts else "未命名数据库"
        return "未命名数据库"
    
    def extract_database_title(self, database_block):
        """提取数据库标题"""
        if 'data' in database_block and 'title' in database_block['data']:
            title_data = database_block['data']['title']
            if isinstance(title_data, str):
                return title_data
            elif isinstance(title_data, list) and len(title_data) > 0:
                # 提取富文本内容
                title_parts = []
                for item in title_data:
                    if isinstance(item, dict) and 'text' in item and 'content' in item['text']:
                        title_parts.append(item['text']['content'])
                    elif isinstance(item, dict) and 'plain_text' in item:
                        title_parts.append(item['plain_text'])
                return ''.join(title_parts) if title_parts else "未命名数据库"
        return "未命名数据库"
    
    def get_database_content(self, database_id):
        """获取数据库内容，使用 after_created_at 过滤最近一个月的记录"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            # 计算一个月前的时间戳（秒级）
            one_month_ago = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=self.database_config['recent_days'])
            after_created_at_timestamp = int(one_month_ago.timestamp())
            
            # 构建查询请求体，使用 after_created_at 过滤
            payload = json.dumps({
                "page_size": 100,  # 设置为最大100条
                "after_created_at": after_created_at_timestamp
            })
            
            request_url = f"/v1/databases/{database_id}/query"
            conn.request("POST", request_url, payload, headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                response_data = json.loads(data.decode("utf-8"))
                print(f"获取到 {len(response_data.get('results', []))} 条最近 {self.database_config['recent_days']} 天的记录")
                return response_data
            else:
                print(f"获取数据库内容失败，状态码: {res.status}")
                print(f"响应内容: {data.decode('utf-8')}")
                return None
                
        except Exception as e:
            print(f"获取数据库内容时出错: {e}")
            return None
    
    def get_relation_content(self, relation_property):
        """获取关系属性的内容"""
        if not relation_property or 'relation' not in relation_property:
            return ""
        
        relation_items = relation_property['relation']
        if not relation_items:
            return ""
        
        relation_content = []
        
        for relation_item in relation_items[:3]:  # 限制最多获取3个关联页面
            page_id = relation_item.get('id')
            if page_id:
                page_title = self.get_page_title_by_id(page_id)
                # 获取页面详细信息，包括所有属性
                page_details = self.get_page_details(page_id)
                
                if page_details:
                    # 格式化页面详细信息
                    formatted_page = self.format_page_details(page_details)
                    relation_content.append(f"关联页面: {page_title}\n{formatted_page}")
                else:
                    relation_content.append(f"关联页面: {page_title} (无法获取内容)")
        
        return '\n\n'.join(relation_content)
    
    def format_page_details(self, page_data):
        """格式化页面详细信息为文本"""
        if not page_data or 'properties' not in page_data:
            return "无属性信息"
        
        formatted_content = []
        
        # 添加页面基本信息
        if 'created_time' in page_data:
            formatted_content.append(f"创建时间: {page_data['created_time']}")
        if 'last_edited_time' in page_data:
            formatted_content.append(f"最后编辑时间: {page_data['last_edited_time']}")
        
        # 处理所有属性
        for prop_name, prop_value in page_data['properties'].items():
            prop_text = self.format_property_value(prop_value)
            if prop_text:
                formatted_content.append(f"{prop_name}: {prop_text}")
        
        return '\n'.join(formatted_content)
    
    def format_database_content(self, database_info, database_content):
        """格式化数据库内容为文本"""
        if not database_content or 'results' not in database_content:
            return f"数据库 '{database_info['title']}' 为空或无法访问"
        
        formatted_content = [f"数据库: {database_info['title']} (来源: {database_info['source']})"]
        formatted_content.append(f"筛选条件: 最近 {self.database_config['recent_days']} 天内创建的记录")
        formatted_content.append("=" * 60)
        
        for i, record in enumerate(database_content['results'], 1):
            formatted_content.append(f"\n记录 {i} (创建于: {record.get('created_time', '未知时间')}):")
            
            # 获取记录的详细信息
            record_details = self.get_page_details(record['id'])
            if record_details and 'properties' in record_details:
                for prop_name, prop_value in record_details['properties'].items():
                    prop_text = self.format_property_value(prop_value)
                    if prop_text:
                        formatted_content.append(f"  {prop_name}: {prop_text}")
        
        return '\n'.join(formatted_content)
    
    def format_property_value(self, property_value):
        """格式化属性值为文本"""
        if not property_value:
            return ""
        
        prop_type = property_value.get('type')
        
        if prop_type == 'title':
            titles = property_value.get('title', [])
            if titles:
                return ' '.join([item.get('plain_text', '') for item in titles if item.get('plain_text')])
        
        elif prop_type == 'rich_text':
            rich_texts = property_value.get('rich_text', [])
            if rich_texts:
                return ' '.join([item.get('plain_text', '') for item in rich_texts if item.get('plain_text')])
        
        elif prop_type == 'number':
            return str(property_value.get('number', ''))
        
        elif prop_type == 'select':
            select_value = property_value.get('select')
            if select_value and 'name' in select_value:
                return select_value['name']
            return ""
        
        elif prop_type == 'multi_select':
            multi_selects = property_value.get('multi_select', [])
            if multi_selects:
                return ', '.join([item.get('name', '') for item in multi_selects if item.get('name')])
            return ""
        
        elif prop_type == 'date':
            date_value = property_value.get('date')
            if date_value:
                start = date_value.get('start', '')
                end = date_value.get('end', '')
                if end:
                    return f"{start} 到 {end}"
                else:
                    return start
            return ""
        
        elif prop_type == 'checkbox':
            return "是" if property_value.get('checkbox') else "否"
        
        elif prop_type == 'url':
            return property_value.get('url', '')
        
        elif prop_type == 'email':
            return property_value.get('email', '')
        
        elif prop_type == 'phone_number':
            return property_value.get('phone_number', '')
        
        elif prop_type == 'people':
            people = property_value.get('people', [])
            if people:
                return ', '.join([person.get('id', '') for person in people])
            return ""
        
        elif prop_type == 'files':
            files = property_value.get('files', [])
            if files:
                return ', '.join([file.get('name', '') for file in files])
            return ""
        
        elif prop_type == 'status':
            status_value = property_value.get('status')
            if status_value and 'name' in status_value:
                return status_value['name']
            return ""
        
        elif prop_type == 'relation' and self.database_config['fetch_relations']:
            # 处理关系属性
            relation_content = self.get_relation_content(property_value)
            if relation_content:
                return f"\n关联内容:\n{relation_content}"
            else:
                relation_count = len(property_value.get('relation', []))
                return f"[{relation_count}个关联页面]"
        
        elif prop_type == 'formula':
            formula_value = property_value.get('formula')
            if formula_value:
                if formula_value.get('type') == 'string':
                    return formula_value.get('string', '')
                elif formula_value.get('type') == 'number':
                    return str(formula_value.get('number', ''))
                elif formula_value.get('type') == 'boolean':
                    return "是" if formula_value.get('boolean') else "否"
                elif formula_value.get('type') == 'date':
                    date_value = formula_value.get('date')
                    if date_value:
                        start = date_value.get('start', '')
                        end = date_value.get('end', '')
                        if end:
                            return f"{start} 到 {end}"
                        else:
                            return start
        
        elif prop_type == 'rollup':
            rollup_value = property_value.get('rollup')
            if rollup_value:
                if rollup_value.get('type') == 'array':
                    array_items = rollup_value.get('array', [])
                    if array_items:
                        return f"[汇总: {len(array_items)} 项]"
                elif rollup_value.get('type') == 'number':
                    return str(rollup_value.get('number', ''))
                elif rollup_value.get('type') == 'date':
                    date_value = rollup_value.get('date')
                    if date_value:
                        start = date_value.get('start', '')
                        end = date_value.get('end', '')
                        if end:
                            return f"{start} 到 {end}"
                        else:
                            return start
        
        elif prop_type == 'created_time':
            return property_value.get('created_time', '')
        
        elif prop_type == 'last_edited_time':
            return property_value.get('last_edited_time', '')
        
        elif prop_type == 'created_by':
            created_by = property_value.get('created_by')
            if created_by and 'id' in created_by:
                return created_by['id']
            return ""
        
        elif prop_type == 'last_edited_by':
            last_edited_by = property_value.get('last_edited_by')
            if last_edited_by and 'id' in last_edited_by:
                return last_edited_by['id']
            return ""
        
        return f"[{prop_type}类型属性]"
    
    def extract_text_from_blocks(self, blocks_data):
        """从块数据中提取文本内容"""
        text_content = []
        
        if blocks_data and 'results' in blocks_data:
            # 首先提取普通文本内容
            for block in blocks_data['results']:
                if block['type'] == 'paragraph' and 'data' in block:
                    rich_text = block['data'].get('rich_text', [])
                    block_text = []
                    for text_item in rich_text:
                        if text_item['type'] == 'text' and 'plain_text' in text_item and text_item['plain_text']:
                            block_text.append(text_item['plain_text'])
                        elif (text_item['type'] == 'mention' and 
                              'mention' in text_item and 
                              text_item['mention']['type'] == 'page'):
                            # 对于页面提及，暂时不处理，会在数据库部分统一处理
                            pass
                    if block_text:
                        text_content.append(''.join(block_text))
            
            # 如果启用了数据库支持，提取数据库内容
            if self.database_config['enabled']:
                database_blocks = self.extract_database_info_from_blocks(blocks_data)
                if database_blocks:
                    text_content.append("\n" + "="*60)
                    text_content.append("关联数据库内容:")
                    text_content.append("="*60)
                    
                    for db_info in database_blocks:
                        print(f"处理数据库: {db_info['title']} (ID: {db_info['id']}, 来源: {db_info['source']})")
                        db_content = self.get_database_content(db_info['id'])
                        if db_content:
                            formatted_db_content = self.format_database_content(db_info, db_content)
                            text_content.append(formatted_db_content)
                        else:
                            text_content.append(f"数据库 '{db_info['title']}' 内容获取失败")
        
        return '\n'.join(text_content)
    
    def save_to_log_file(self, content, filename=None):
        """保存内容到日志文件"""
        if filename is None:
            filename = self.log_filename
            
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"原始内容已保存到 {os.path.abspath(filename)}")
        except Exception as e:
            print(f"保存日志文件时出错: {e}")
    
    def send_to_siliconflow(self, content):
        """发送内容到硅基流动API"""
        try:
            conn = http.client.HTTPSConnection("api.siliconflow.cn")
            
            # 使用配置文件中的API设置
            api_settings = self.config['api_settings']
            
            payload = json.dumps({
                "model": self.config['siliconflow']['model'],
                "messages": [
                    {
                        "role": "user",
                        "content": content
                    }
                ],
                "stream": False,
                "max_tokens": api_settings['max_tokens'],
                "enable_thinking": False,
                "thinking_budget": 4096,
                "min_p": 0.05,
                "stop": None,
                "temperature": api_settings['temperature'],
                "top_p": api_settings['top_p'],
                "top_k": api_settings['top_k'],
                "frequency_penalty": api_settings['frequency_penalty'],
                "n": 1,
                "response_format": {
                    "type": "text"
                }
            })
            
            headers = {
                'Authorization': self.siliconflow_token,
                'Content-Type': 'application/json'
            }
            
            conn.request("POST", "/v1/chat/completions", payload, headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                response_data = json.loads(data.decode("utf-8"))
                return response_data
            else:
                print(f"硅基流动API请求失败，状态码: {res.status}")
                print(f"响应内容: {data.decode('utf-8')}")
                return None
                
        except Exception as e:
            print(f"发送到硅基流动API时出错: {e}")
            return None
    
    def create_flowus_page(self, title):
        """在FlowUs中创建新页面"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            
            # 构建请求体
            payload = json.dumps({
                "parent": {
                    "page_id": self.parent_page_id
                },
                "properties": {
                    "title": {
                        "type": "title",
                        "title": [
                            {
                                "text": {
                                    "content": title
                                }
                            }
                        ]
                    }
                },
                "icon": {
                    "emoji": self.new_page_config['icon_emoji']
                }
            })
            
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            conn.request("POST", "/v1/pages", payload, headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                response_data = json.loads(data.decode("utf-8"))
                print(f"成功创建新页面: {title}")
                print(f"页面URL: {response_data.get('url', 'N/A')}")
                return response_data
            else:
                print(f"创建FlowUs页面失败，状态码: {res.status}")
                print(f"响应内容: {data.decode('utf-8')}")
                return None
                
        except Exception as e:
            print(f"创建FlowUs页面时出错: {e}")
            return None
    
    def append_blocks_to_page(self, page_id, ai_response, silicon_response):
        """向页面追加块内容（不包含原始输入内容）"""
        try:
            conn = http.client.HTTPSConnection("api.flowus.cn")
            
            # 构建块内容
            children = []
            
            # 1. 添加AI回复标题
            children.append({
                "type": "heading_2",
                "data": {
                    "rich_text": [
                        {
                            "type": "text",
                            "text": {
                                "content": "AI回复内容",
                                "link": None
                            },
                            "annotations": {
                                "bold": True,
                                "color": "green"
                            }
                        }
                    ],
                    "text_color": "green",
                    "background_color": "default"
                }
            })
            
            # 2. 添加AI回复内容（按段落分割）
            ai_paragraphs = ai_response.split('\n\n')
            for paragraph in ai_paragraphs:
                if paragraph.strip():
                    children.append({
                        "type": "paragraph",
                        "data": {
                            "rich_text": [
                                {
                                    "type": "text",
                                    "text": {
                                        "content": paragraph.strip(),
                                        "link": None
                                    }
                                }
                            ],
                            "text_color": self.block_settings['text_color'],
                            "background_color": self.block_settings['background_color']
                        }
                    })
            
            # 3. 添加元数据
            if self.block_settings['include_metadata']:
                children.append({
                    "type": "divider",
                    "data": {}
                })
                
                children.append({
                    "type": "callout",
                    "data": {
                        "rich_text": [
                            {
                                "type": "text",
                                "text": {
                                    "content": "生成信息",
                                    "link": None
                                },
                                "annotations": {
                                    "bold": True
                                }
                            },
                            {
                                "type": "text",
                                "text": {
                                    "content": f"\n模型: {silicon_response.get('model', 'N/A')}\n响应ID: {silicon_response.get('id', 'N/A')}\n生成时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                                    "link": None
                                }
                            }
                        ],
                        "icon": {
                            "emoji": "ℹ️"
                        },
                        "text_color": "default",
                        "background_color": "gray"
                    }
                })
            
            # 构建请求体
            payload = json.dumps({
                "children": children
            })
            
            headers = {
                'Authorization': self.flowus_token,
                'Content-Type': 'application/json'
            }
            
            request_url = f"/v1/blocks/{page_id}/children"
            conn.request("PATCH", request_url, payload, headers)
            res = conn.getresponse()
            data = res.read()
            
            if res.status == 200:
                response_data = json.loads(data.decode("utf-8"))
                print(f"成功向页面添加 {len(children)} 个内容块")
                return response_data
            else:
                print(f"追加块内容失败，状态码: {res.status}")
                print(f"响应内容: {data.decode('utf-8')}")
                return None
                
        except Exception as e:
            print(f"追加块内容时出错: {e}")
            return None
    
    def save_to_markdown(self, content, filename=None):
        """保存内容到Markdown文件"""
        if filename is None:
            filename = self.output_filename
            
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"内容已保存到 {os.path.abspath(filename)}")
        except Exception as e:
            print(f"保存文件时出错: {e}")
    
    def run(self):
        """主执行函数"""
        print("开始从FlowUs获取页面内容...")
        
        # 1. 获取FlowUs页面内容
        blocks_data = self.get_flowus_page_content()
        if not blocks_data:
            print("无法获取FlowUs页面内容")
            return
        
        print("成功获取FlowUs页面内容")
        
        # 2. 提取文本内容（包括数据库内容）
        extracted_text = self.extract_text_from_blocks(blocks_data)
        if not extracted_text:
            print("未从页面中提取到文本内容")
            return
        
        print(f"提取的文本内容长度: {len(extracted_text)} 字符")
        print("提取的内容预览:")
        print("=" * 50)
        print(extracted_text[:500] + "..." if len(extracted_text) > 500 else extracted_text)
        print("=" * 50)
        
        # 3. 保存原始内容到日志文件
        print(f"保存原始内容到 {self.log_filename}...")
        self.save_to_log_file(extracted_text)
        
        # 4. 发送到硅基流动API
        print("发送内容到硅基流动API...")
        silicon_response = self.send_to_siliconflow(extracted_text)
        if not silicon_response:
            print("硅基流动API请求失败")
            return
        
        print("成功获取硅基流动API响应")
        
        # 5. 提取回复内容
        if 'choices' in silicon_response and len(silicon_response['choices']) > 0:
            reply_content = silicon_response['choices'][0]['message']['content']
            
            # 创建Markdown格式的内容
            markdown_content = (
                "# 硅基流动API回复\n\n"
                "## 原始输入内容\n"
                f"```\n{extracted_text}\n```\n\n"
                "## AI回复\n"
                f"{reply_content}\n\n"
                "## 响应信息\n"
                f"- 模型: {silicon_response.get('model', 'N/A')}\n"
                f"- 响应ID: {silicon_response.get('id', 'N/A')}\n"
                f"- 创建时间: {silicon_response.get('created', 'N/A')}\n"
            )
            
            # 6. 保存到文件
            self.save_to_markdown(markdown_content)
            
            print("\nAI回复内容:")
            print("=" * 50)
            print(reply_content)
            print("=" * 50)
            
            # 7. 在FlowUs中创建新页面
            print(f"\n在父页面 {self.parent_page_id} 下创建新页面...")
            page_title = f"{self.new_page_config['title']} - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
            page_response = self.create_flowus_page(page_title)
            
            if page_response:
                new_page_id = page_response.get('id')
                print(f"新页面创建成功，ID: {new_page_id}")
                
                # 8. 向新页面追加块内容（只包含AI回复，不包含原始内容）
                print("向新页面添加块内容...")
                blocks_response = self.append_blocks_to_page(
                    new_page_id, 
                    reply_content, 
                    silicon_response
                )
                
                if blocks_response:
                    print("内容块添加成功！")
                else:
                    print("内容块添加失败")
            else:
                print("新页面创建失败")
            
        else:
            print("无法从API响应中提取回复内容")

if __name__ == "__main__":
    try:
        processor = FlowUsToSiliconFlow()
        processor.run()
    except Exception as e:
        print(f"程序初始化失败: {e}")43806@qq.com